package com.century.sjt.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.AboutSJTActivity;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.activity.Pay.MerchantActivity;
import com.century.sjt.activity.MyActivity;
import com.century.sjt.activity.MyQRRecordActivity;
import com.century.sjt.activity.QRRecordCodeScanActivity;
import com.century.sjt.activity.Topic.MySocialZoneNewActivity;
import com.century.sjt.util.Constant;
import com.century.sjt.util.SIMCardInfo;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.HomeTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;


public class FragmentDiscover extends BaseFragment implements View.OnClickListener{
    private Context mContext;
    private HomeTitleBar titleBar;
    MainActivity mMainActivity;

    @BindView(R.id.find_friend)
    LinearLayout  find_friend;
    @BindView(R.id.find_scan)
    LinearLayout find_scan;
    @BindView(R.id.find_MaxCard)
    LinearLayout find_MaxCard;
    @BindView(R.id.find_shopping)
    LinearLayout find_shopping;
//    @BindView(R.id.find_bank)
//    LinearLayout find_bank;
    @BindView(R.id.find_aboutsit)
    LinearLayout find_aboutsit;
    @BindView(R.id.overseas_ambassador)
    LinearLayout overseas_ambassador;
    @BindView(R.id.sjt_csphone)
    LinearLayout sjt_csphone;
    private long LastTime;
    private long inTime;
    private String countryCode;
    private RequestQueue mQueue;
    private String chineseName;
    private String chineseEmbassytel;
    private String sjtServiceTel;
    public FragmentDiscover() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_discover, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ButterKnife.bind(this,getView());
        mQueue = Volley.newRequestQueue(getActivity());
        mMainActivity= (MainActivity) getActivity();
        initView();
        initEvents();
    }


    private void initView() {
        titleBar = (HomeTitleBar) getView().findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.text_discover));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MyActivity.class);
                startActivity(intent);
            }
        });
    }
    /**
     * @Description:绑定监听
     * @author: 周玲波
     * @date: 2016/8/16 19:32
     */
    private void initEvents() {
        find_friend.setOnClickListener(this);
        find_scan.setOnClickListener(this);
        find_MaxCard.setOnClickListener(this);
        find_shopping.setOnClickListener(this);
       // find_bank.setOnClickListener(this);
        find_aboutsit.setOnClickListener(this);
        overseas_ambassador.setOnClickListener(this);
        sjt_csphone.setOnClickListener(this);
    }
    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {
     switch (v.getId()){
         case R.id.find_friend://朋友圈
             Intent intent = new Intent(getActivity(), MySocialZoneNewActivity.class);
             startActivity(intent);
             break;
         case R.id.find_scan://扫一扫
             ((MainActivity)getActivity()).startActivity(getActivity(), QRRecordCodeScanActivity.class);
             break;
         case R.id.find_MaxCard:
             mMainActivity.startActivity(mMainActivity, MyQRRecordActivity.class);
             break;
         case R.id.find_shopping://商家购物
             Intent intent3 = new Intent();
             intent3.setClass(getActivity(), MerchantActivity.class);
             intent3.putExtra("payType", "1");
             startActivity(intent3);
             break;
//         case R.id.find_bank:
//             mMainActivity.startActivity(mMainActivity, AboutSJTcBank.class);
//             break;
         case R.id.find_aboutsit:
             mMainActivity.startActivity(mMainActivity, AboutSJTActivity.class);
             break;

         case R.id.overseas_ambassador:

//             联系大使馆
             inTime = System.currentTimeMillis();
             if (inTime-LastTime>60000){
                 GetIpInfo("1");
             }else {
                 if ("".equals(countryCode)||null==countryCode){
                     GetIpInfo("1");
                 }else {
                     showDial("驻"+chineseName+"大使馆电话",chineseEmbassytel);
                 }
             }
             break;
         case R.id.sjt_csphone:
             //世纪通客服
             inTime = System.currentTimeMillis();
             if (inTime-LastTime>60000){
                 GetIpInfo("2");
             }else {
                 if ("".equals(countryCode)||null==countryCode){
                     GetIpInfo("2");
                 }else {
                     showDial("客服电话",sjtServiceTel);
                 }
             }
             break;
     }
    }
    public void GetIpInfo(final String isOn){
        String Ip = "";
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.GetIPInfo + "myip", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    JSONObject Data = res.getJSONObject("data");
                    if (code.equals("0")) {//成功
                        LastTime = System.currentTimeMillis();
                        String country_id = Data.getString("country_id");
                        if (null==countryCode||"".equals(countryCode)){
                            OneTouchCalling(isOn,country_id);
                        }else if (countryCode.equals(country_id)){
                            switch (isOn){
                                case "1":
                                    showDial("驻"+chineseName+"大使馆电话",chineseEmbassytel);
                                    break;
                                case "2":
                                    showDial("客服电话",sjtServiceTel);
                                    break;
                                default:
                                    break;
                            }
                        }else {
                            OneTouchCalling(isOn,country_id);
                        }

                    } else {//失败
//                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
//                SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
//                map.put("latitude", latitude);
//                map.put("longitude", longitude);
                return map;
            }

        };
        mQueue.add(stringRequest);
    }
    /**
     * 获取关于世纪通的信息
     */
    private void OneTouchCalling(final String isOn,final String country_id) {
        //显示Progress Dialog
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getCountryInfo, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject Data = res.getJSONObject("data");
                    if (code.equals("200")) {//成功

                        countryCode = Data.getString("countryCode");
                        chineseName = Data.getString("chineseName");
                        chineseEmbassytel = Data.getString("chineseEmbassytel");
                        sjtServiceTel = Data.getString("sjtServiceTel");
                        if (null==sjtServiceTel||"".equals(sjtServiceTel)||null== chineseEmbassytel||"".equals(chineseEmbassytel)){
                            switch (isOn){
                                case "1":
                                    Toast.makeText(getActivity(),"获取不到当地大使馆电话",Toast.LENGTH_LONG).show();
                                    break;
                                case "2":
                                    Toast.makeText(getActivity(),"获取不到当地客服电话",Toast.LENGTH_LONG).show();
                                    break;
                                default:

                                    break;
                            }
                        }else {
                            switch (isOn){
                                case "1":
                                    showDial("驻"+chineseName+"大使馆电话",chineseEmbassytel);
                                    break;
                                case "2":
                                    showDial("客服电话",sjtServiceTel);
                                    break;
                                default:
                                    break;
                            }}


                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), getActivity(), 1);
                }

                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
//                SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("countryCode", country_id);
                SIMCardInfo simCardInfo = new SIMCardInfo(getActivity());
//                Log.e("获取设备当前位置",simCardInfo.getCellLocation());
//                Log.e("获取运营商的国家代码",simCardInfo.getNetworkCountryIso());
//                Log.e("获取运营商的名称",simCardInfo.getNetworkOperatorName());
                map.put("networkCountryIso",simCardInfo.getNetworkCountryIso());
                return map;
            }

        };
        mQueue.add(stringRequest);
    }

    public void showDial(final String Name, final String mobile){
        //询问是否拨打
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getResources().getString(R.string.text_prompt));
        builder.setMessage(Name+":"+mobile+"");
        builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
                startActivity(intent);
            }
        });
        builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String image = sharedPreferences.getString("image", "");
        titleBar.setLeftImageResource(getActivity(),Constant.ImageHost_Big + image);
    }
}
